package com.coding.kan_yi_dao.service.impl;

import com.coding.kan_yi_dao.common.Result;
import com.coding.kan_yi_dao.entity.GoodsCategory;
import com.coding.kan_yi_dao.mapper.GoodsCategoryMapper;
import com.coding.kan_yi_dao.service.IGoodsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 砍一刀，不买就砍你一刀
 * @since 2023-09-20
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements IGoodsCategoryService {
    //全查询
    @Override
    public Result go_select() {
        //1.取出全部分类信息
        List<GoodsCategory> categoryList = query().eq("is_deleted",1).list();
        //2.所有的一级分类 stream流 过滤器
        List<GoodsCategory> categories = categoryList.stream()
                .filter(c -> c.getCategoryLevel().equals(1))
                .peek(c -> {
                    //c所有的一级分类
                    c.setChildren(listChildren(c, categoryList));
                })
                .collect(Collectors.toList());
        return Result.ok(categories);
    }

    //修改
    @Override
    public Result go_update(GoodsCategory goodsCategory) {
        return Result.ok(baseMapper.updateById(goodsCategory));
    }

    //删除
    @Override
    public Result go_delete(GoodsCategory goodsCategory) {
        List<GoodsCategory> goodsCategories= query().eq("parent_id",goodsCategory.getCategoryId()).list();
        if (goodsCategories.size()==0){
            return Result.ok(baseMapper.deleteById(goodsCategory));
        }
        return Result.fail("删除失败");
    }

    //添加
    @Override
    public Result go_insert(GoodsCategory goodsCategory) {
        return Result.ok(baseMapper.insert(goodsCategory));
    }

    //通过一个分类寻找子分类集合
    private List<GoodsCategory> listChildren(GoodsCategory category, List<GoodsCategory> all) {
        return all.stream().filter(e -> e.getParentId().equals(category.getCategoryId())).peek(e -> e.setChildren(listChildren(e, all))).collect(Collectors.toList());

    }
}
